package com.qyhl.module_home.home.fragment2.main;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.orhanobut.hawk.Hawk;
import com.qinanyu.bannerview.holder.SimpleHolder;
import com.qinanyu.bannerview.holder.SimpleHolderCreator;
import com.qinanyu.bannerview.listener.OnItemClickListener;
import com.qinanyu.bannerview.view.SimpleBannerView;
import com.qyhl.module_home.R;
import com.qyhl.module_home.R2;
import com.qyhl.module_home.utils.MyGridViewAdapter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.ToastUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.AppConfigConstant;
import com.qyhl.webtv.commonlib.entity.act.ActDetailsBean;
import com.qyhl.webtv.commonlib.entity.broke.ScoopTopicBean;
import com.qyhl.webtv.commonlib.entity.circle.CircleHomeBean;
import com.qyhl.webtv.commonlib.entity.circle.ScoopListBean;
import com.qyhl.webtv.commonlib.entity.home.GatherBean;
import com.qyhl.webtv.commonlib.entity.home.HomeBean;
import com.qyhl.webtv.commonlib.entity.home.NewsBean;
import com.qyhl.webtv.commonlib.entity.live.ShoppingListBean;
import com.qyhl.webtv.commonlib.entity.live.TeleTextBean;
import com.qyhl.webtv.commonlib.entity.news.AdvHomeBean;
import com.qyhl.webtv.commonlib.entity.news.AdvertiseBean;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.entity.news.UnionBean;
import com.qyhl.webtv.commonlib.item.ItemActivity;
import com.qyhl.webtv.commonlib.item.ItemAdvCommon;
import com.qyhl.webtv.commonlib.item.ItemAdvGroup;
import com.qyhl.webtv.commonlib.item.ItemAdvLarge;
import com.qyhl.webtv.commonlib.item.ItemCatchNews;
import com.qyhl.webtv.commonlib.item.ItemCirclePicture;
import com.qyhl.webtv.commonlib.item.ItemCircleText;
import com.qyhl.webtv.commonlib.item.ItemCircleTopic;
import com.qyhl.webtv.commonlib.item.ItemCircleVideo;
import com.qyhl.webtv.commonlib.item.ItemCommonLarge;
import com.qyhl.webtv.commonlib.item.ItemCommonLeft;
import com.qyhl.webtv.commonlib.item.ItemCommonRight;
import com.qyhl.webtv.commonlib.item.ItemCommonThreePics;
import com.qyhl.webtv.commonlib.item.ItemGoodLife;
import com.qyhl.webtv.commonlib.item.ItemNoPicture;
import com.qyhl.webtv.commonlib.item.ItemOtherAdv;
import com.qyhl.webtv.commonlib.item.ItemPicture;
import com.qyhl.webtv.commonlib.item.ItemScoop;
import com.qyhl.webtv.commonlib.item.ItemScoopTopic;
import com.qyhl.webtv.commonlib.item.ItemSmallVideo;
import com.qyhl.webtv.commonlib.item.ItemTeleText;
import com.qyhl.webtv.commonlib.item.ItemTitleNews;
import com.qyhl.webtv.commonlib.item.ItemTopNews;
import com.qyhl.webtv.commonlib.item.ItemTopNoPicture;
import com.qyhl.webtv.commonlib.item.ItemTopShopping;
import com.qyhl.webtv.commonlib.item.ItemUnion;
import com.qyhl.webtv.commonlib.item.ItemUnionLarge;
import com.qyhl.webtv.commonlib.item.ItemVideoLarge;
import com.qyhl.webtv.commonlib.item.ItemVideoLeft;
import com.qyhl.webtv.commonlib.item.ItemVideoRight;
import com.qyhl.webtv.commonlib.utils.ItemSkipUtils;
import com.qyhl.webtv.commonlib.utils.ResizableImageView;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.config.AppConfigUtil;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.expandableView.text.UIUtil;
import com.qyhl.webtv.commonlib.utils.view.gridviewpager.GridViewPager;
import com.qyhl.webtv.commonlib.utils.view.gridviewpager.GridViewPagerDataAdapter;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;

/**
 * 推荐首页
 */
public class HomeListFragment extends Fragment implements HomeListContract.HomeListView {
    @BindView(R2.id.listview)
    RecyclerView listview;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.loading_mask)
    LoadingLayout loadingMask;
    @BindView(R2.id.media_enter)
    ImageView mediaEnter;

    private GridViewPager mNavigation;
    private LinearLayout mPointLayout;
    private RequestOptions options;//glide配置
    private View view;
    private boolean isCreated = false;
    private boolean isVisible = false;
    private boolean isloaded = false;
    private List<GlobalNewsBean> mDataList;
    private List<HomeBean.TopNews> bannerList;
    private SimpleBannerView<HomeBean.TopNews> mBanner;
    private SimpleBannerView<AdvertiseBean> mAdvBanner, mAdvBannerTop;
    private HomeListContract.HomeListViewPresenter presenter;
    private List<AdvertiseBean> advList = new ArrayList<>(), advTopList = new ArrayList<>(), advBottomList = new ArrayList<>();
    private ImageView[] imgs;//动态创建滑动指示器
    private static final float MIN_ALPHA = 0.0f;
    private int page = 1;//请求第x页
    private int lastNewsId = 0;//记录请求最后一条id,加载时从该id后查询
    private List<HomeBean.SecMenus> navigationList = new ArrayList<>();
    private static final int COLUMNS_NUM = 5;//导航栏列数
    private static final int ROWS_NUM = 1;//导航栏行数
    private HeaderAndFooterWrapper<GlobalNewsBean> mHeaderAndFooterWrapper;
    private String lastType = "0";
    private int topNum = 0;

    private boolean hasBottomAdv;

    private ResizableImageView answerCover;

    private ResizableImageView partyEnter;

    private ResizableImageView classicEnter;
    private CardView classicEnterLayout;

    private int[] indexPosition = new int[]{6, 17, 28, 39, 50, 61, 72, 83};

    private int idNum = 0;

    private boolean isCache;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isVisible = true;
            lazyLoad();
        }
    }

    @SuppressLint("InflateParams")
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.home_fragment_home_tab, null);
            ButterKnife.bind(this, view);
            presenter = new HomeListPresenterImpl(this);
            initview();
            isCreated = true;
            initCache();
            lazyLoad();
        }
        return view;
    }

    /**
     * 加载缓存
     */
    private void initCache() {
        //快速入口缓存
        if (Hawk.contains("home")) {
            HomeBean bean = Hawk.get("home");
            if (bean == null) {
                Hawk.delete("home");
                return;
            }
            List<HomeBean.TopNews> topNewsList = bean.getTopNews();
            List<HomeBean.SecMenus> threeMenus = bean.getSecMenus();
            //是否显示轮播
            if (topNewsList != null && topNewsList.size() != 0) {
                setBanner(true, topNewsList);
            } else {
                setBanner(false, null);
            }

            //是否显示导航
            if (threeMenus != null && threeMenus.size() != 0) {
                setNavigation(true, threeMenus);
            } else {
                setNavigation(false, null);
            }
        }

        if (Hawk.contains("gather")) {
            /*
             * 是否是缓存数据
             */
            isCache = true;
            List<GatherBean> bean = Hawk.get("gather");
            try {
                setGatherNews(bean, false);//启用缓存数据
            } catch (Exception e) {
                Hawk.delete("gather");
            }
            isCache = false;
        }


        //广告缓存
        if (Hawk.contains("homeAdv")) {
            List<AdvHomeBean> bean = Hawk.get("homeAdv");
            setAdvBanner(true, bean);
        }
        page = 1;
        lastNewsId = 0;
        lastType = "0";
    }

    @SuppressLint("InflateParams")
    private void initview() {
        loadingMask.setStatus(LoadingLayout.Loading);

        if (CommonUtils.getInstance().getSite() == 31) {
            mediaEnter.setVisibility(View.VISIBLE);
            mediaEnter.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putString("title", "融媒");
                RouterManager.router(ARouterPathConstant.JL_MULTI_LIST, bundle);


            });
        } else {
            mediaEnter.setVisibility(View.GONE);
        }
        //glide配置
        options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.cover_large_default)
                .error(R.drawable.cover_large_default);
        //配置刷新控件
        refresh.setEnableLoadMore(true);
        refresh.setRefreshHeader(new MaterialHeader(Objects.requireNonNull(getContext())));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));

        View headView = LayoutInflater.from(getContext()).inflate(R.layout.home_header_homefragment2, null);

        mNavigation = (GridViewPager) headView.findViewById(R.id.navigation);
        mPointLayout = (LinearLayout) headView.findViewById(R.id.point_layout);
        mBanner = (SimpleBannerView) headView.findViewById(R.id.banner);
        mAdvBanner = (SimpleBannerView) headView.findViewById(R.id.adv_banner_middle);
        mAdvBannerTop = (SimpleBannerView) headView.findViewById(R.id.adv_banner_top);
        classicEnter = (ResizableImageView) headView.findViewById(R.id.classic_enter);
        classicEnterLayout = (CardView) headView.findViewById(R.id.classic_enter_layout);
        answerCover = (ResizableImageView) headView.findViewById(R.id.answer_cover);
        partyEnter = (ResizableImageView) headView.findViewById(R.id.party_enter);
        mDataList = new ArrayList<>();
        LinearLayoutManager mLayoutManager;
        listview.setLayoutManager(mLayoutManager = new LinearLayoutManager(getContext()));
        listview.addItemDecoration(new com.luck.picture.lib.decoration.RecycleViewDivider(
                getContext(), LinearLayoutManager.HORIZONTAL, 1, ContextCompat.getColor(getContext(), R.color.global_gray_lv3)));


        MultiItemTypeAdapter<GlobalNewsBean> mAdapter = new MultiItemTypeAdapter<GlobalNewsBean>(getContext(), mDataList);
        mAdapter.addItemViewDelegate(new ItemAdvCommon(getContext()));
        mAdapter.addItemViewDelegate(new ItemAdvGroup(getContext()));
        mAdapter.addItemViewDelegate(new ItemAdvLarge(getContext()));
        mAdapter.addItemViewDelegate(new ItemCatchNews(getContext()));
        mAdapter.addItemViewDelegate(new ItemCommonLarge(getContext()));
        mAdapter.addItemViewDelegate(new ItemCommonRight(getContext()));
        mAdapter.addItemViewDelegate(new ItemCommonLeft(getContext()));
        mAdapter.addItemViewDelegate(new ItemGoodLife(getContext()));
        mAdapter.addItemViewDelegate(new ItemNoPicture(getContext()));
        mAdapter.addItemViewDelegate(new ItemPicture(getContext()));
        mAdapter.addItemViewDelegate(new ItemTitleNews(getContext()));
        mAdapter.addItemViewDelegate(new ItemTopNews(getContext()));
        mAdapter.addItemViewDelegate(new ItemTopNoPicture(getContext()));
        mAdapter.addItemViewDelegate(new ItemVideoLarge(getContext()));
        mAdapter.addItemViewDelegate(new ItemVideoLeft(getContext()));
        mAdapter.addItemViewDelegate(new ItemVideoRight(getContext()));
        mAdapter.addItemViewDelegate(new ItemUnionLarge(getContext()));
        mAdapter.addItemViewDelegate(new ItemSmallVideo(getContext()));
        mAdapter.addItemViewDelegate(new ItemUnion(getContext()));
        mAdapter.addItemViewDelegate(new ItemTeleText(getContext()));
        mAdapter.addItemViewDelegate(new ItemCommonThreePics(getContext()));
        mAdapter.addItemViewDelegate(new ItemCircleVideo(getContext()));
        mAdapter.addItemViewDelegate(new ItemCirclePicture(getContext()));
        mAdapter.addItemViewDelegate(new ItemCircleText());
        mAdapter.addItemViewDelegate(new ItemCircleTopic(getContext()));
        mAdapter.addItemViewDelegate(new ItemScoop());
        mAdapter.addItemViewDelegate(new ItemScoopTopic());
        mAdapter.addItemViewDelegate(new ItemActivity(getContext()));
        mAdapter.addItemViewDelegate(new ItemOtherAdv(getActivity()));
        mAdapter.addItemViewDelegate(new ItemTopShopping(getActivity()));
        mHeaderAndFooterWrapper = new HeaderAndFooterWrapper(mAdapter);
        mHeaderAndFooterWrapper.addHeaderView(headView);
        listview.setAdapter(mHeaderAndFooterWrapper);
        mHeaderAndFooterWrapper.notifyDataSetChanged();

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                GlobalNewsBean bean = null;
                if (position >= 0) {
                    if (listview.getAdapter().getItemCount() == mDataList.size()) {
                        bean = mDataList.get(position);
                    } else {
                        if (position != 0) {
                            bean = mDataList.get(position - 1);
                        }
                    }
                }
                ItemSkipUtils.getInstance().itemSkip(bean, getContext(), view);
                if (CommonUtils.getInstance().getHasHistory()) {
                    //设置已读，保存记录于本地
                    Map<String, String> historyMap;
                    if (Hawk.contains("readHistory")) {
                        historyMap = CommonUtils.getInstance().getReadHistory();
                    } else {
                        historyMap = new HashMap<>();
                    }
                    historyMap.put(bean.getNewsId(), DateUtils.getCurrentTime());
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.READ_HISTORY, historyMap);
                    Hawk.put("readHistory", historyMap);
                    mHeaderAndFooterWrapper.notifyItemChanged(position);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        setListener();
    }

    private void setListener() {
        //重新加载
        loadingMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadingMask.setReloadButtonText("加载中...");
                page = 1;
                lastNewsId = 0;
                lastType = "0";
                presenter.getConfig();
                presenter.getAdvData();
                getData();//获取首页新闻
            }
        });
        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                lastNewsId = 0;
                lastType = "0";
                presenter.getConfig();
                presenter.getAdvData();
                getData();
            }
        });

        //加载更多
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                page++;
                getData();
            }
        });

        //轮播点击
        //1:普通新闻 2:图片新闻 3:视频新闻 4:广告 5:互动直播  6:新趣汇 7:小视频 8:标题新闻 9:普通直播 10.抓取新闻 11.投票活动 12.线下活动
        mBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                HomeBean.TopNews bean = bannerList.get(position);
                String type = null;
                switch (bean.getType()) {
                    //活动
                    case "0":
                        if ("1".equals(bean.getActivityJson().getType())) {
                            type = "11";
                        } else {
                            type = "12";
                        }
                        break;
                    //普通
                    case "1":
                        type = "1";
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOPNEWS);
                        break;
                    //图片
                    case "2":
                        type = "2";
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOPNEWS);
                        break;
                    //直播
                    case "3":
                        type = "9";
                        break;
                    //标题
                    case "4":
                        type = "8";
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOPNEWS);
                        break;
                    //视频
                    case "5":
                        type = "3";
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOPNEWS);
                        break;
                    case "101"://抓取新闻
                        type = "10";
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOPRECOMMENDNEWS);
                        break;
                    case "102"://小视频
                        type = "7";
                        break;
                    default:
                        break;

                }
                GlobalNewsBean globalNewsBean = new GlobalNewsBean(bean.getArticleTitle(), bean.getArticleID(), bean.getArticleURL(), bean.getArticleImg(), 0, null, bean.getType(), 0, null, bean.getCatalogID(), false, type, bean.getLivetype());
                ItemSkipUtils.getInstance().itemTopSkip(globalNewsBean, getContext());
            }
        });

        //广告点击
        mAdvBanner.setOnItemClickListener(position -> {
            AdvertiseBean advertiseBean = advList.get(position);
            advSkip(advertiseBean);
        });

        mAdvBannerTop.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                AdvertiseBean advertiseBean = advTopList.get(position);
                advSkip(advertiseBean);
            }
        });

        //导航栏滑动监听
        mNavigation.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setIndicator(position);//设置滑动指示器
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void advSkip(AdvertiseBean advertiseBean) {
        if (StringUtils.isEmpty(advertiseBean.getLink())) {
            switch (advertiseBean.getLinkType()) {
                case "1": {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", advertiseBean.getLinkId());
                    RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY, bundle);
                }
                break;
                case "2": {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", advertiseBean.getLinkId());
                    RouterManager.router(ARouterPathConstant.SCOOP_DETAIL_ACTIVIT, bundle);
                }
                break;
                case "3":
                    switch (advertiseBean.getContentType()) {
                        case "1": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY, bundle);
                        }
                        break;
                        case "2": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            bundle.putString("section", advertiseBean.getCatalogID());
                            RouterManager.router(ARouterPathConstant.PICTURE_NEWS_ACTIVITY, bundle);
                        }
                        break;
                        case "3":
                            break;
                        case "4":
                            break;
                        case "5": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY, bundle);
                        }
                        break;
                        case "8": {
                        }
                        break;
                        case "101": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            RouterManager.router(ARouterPathConstant.NEWS_CATCH, bundle);
                        }
                        break;
                        default:
                            break;
                    }
                    break;
                case "4": {
                    Bundle bundle = new Bundle();
                    bundle.putString("actId", advertiseBean.getLinkId());
                    RouterManager.router(ARouterPathConstant.ACT_DETAILS, bundle);
                    ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.ACTIVITY_DETAIL);
                }
                break;
                case "5": {
                    Bundle bundle = new Bundle();
                    String userName = CommonUtils.getInstance().getUserName();
                    bundle.putString("userName", userName);
                    bundle.putInt("id", Integer.parseInt(advertiseBean.getLinkId()));
                    RouterManager.routerLoginInterceptor(getContext(), bundle, ARouterPathConstant.NINE_LUCK_DRAW);
                    ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.LOTTERY);
                }
                break;
                default:
                    break;

            }
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("title", advertiseBean.getTitle());
            bundle.putString("id", advertiseBean.getId() + "");
            bundle.putString("url", advertiseBean.getLink());
            bundle.putBoolean("hasJS", true);
            if (advertiseBean.getIsShare() != null && "0".equals(advertiseBean.getIsShare())) {
                bundle.putBoolean("hasShare", false);
            }
            RouterManager.router(ARouterPathConstant.ADV, bundle);
        }
        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.ADV);
    }

    private void lazyLoad() {
        if (isCreated && isVisible && !isloaded) {
            isloaded = true;
            presenter.getConfig();
            presenter.getAdvData();
            getData();//获取首页新闻
        }
    }

    @Override
    public void setBanner(boolean isShow, List<HomeBean.TopNews> list) {
        int bannerNum = CommonUtils.getInstance().getBannerNum();
        if (isShow && bannerNum != 0) {
            bannerList = new ArrayList<>();
            if (list.size() <= bannerNum) {
                bannerList = list;
            } else {
                for (int i = 0; i < bannerNum; i++) {
                    bannerList.add(list.get(i));
                }
            }
            mBanner.setVisibility(View.VISIBLE);
            List<String> titleNames = new ArrayList<>();
            for (int i = 0; i < bannerList.size(); i++) {
                titleNames.add(bannerList.get(i).getArticleTitle());
            }
            String[] titleStrings = new String[titleNames.size()];
            titleNames.toArray(titleStrings);
            //当只有一张轮播图时
            if (bannerList.size() == 1) {
                mBanner.setTextBanner(titleStrings[0]);
                mBanner.setCanLoop(false);//停止轮播
            }

            mBanner.setPages(new SimpleHolderCreator() {
                @Override
                public Object createHolder() {
                    return new BannerImageHolderView();
                }
            }, bannerList)
                    .startTurning(3000)//轮播3s一次
                    .setPageIndicator(new int[]{R.drawable.home_banner_indicator_off, R.drawable.home_banner_indicator_on}, titleStrings)
                    .setPageIndicatorAlign(SimpleBannerView.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
        } else {
            mBanner.setVisibility(View.GONE);
        }
    }

    @Override
    public void setAdvBanner(boolean isShow, List<AdvHomeBean> list) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        if (isShow) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getPosition().equals("1")) {//下
                    if (list.get(i).getAdvertise() != null && list.get(i).getAdvertise().size() > 0) {
                        hasBottomAdv = true;
                        advBottomList.clear();
                        advBottomList.addAll(list.get(i).getAdvertise());
                    } else {
                        hasBottomAdv = false;
                    }
                } else if (list.get(i).getPosition().equals("2")) {//中
                    if (list.get(i).getAdvertise() != null && list.get(i).getAdvertise().size() > 0) {
                        advList.clear();
                        advList.addAll(list.get(i).getAdvertise());
                        mAdvBanner.setVisibility(View.VISIBLE);
                        if (advList.size() == 0) {
                            mAdvBanner.setVisibility(View.GONE);
                        } else if (advList.size() == 1) {  //一张图时关闭轮播
                            mAdvBanner.setVisibility(View.VISIBLE);
                            mAdvBanner.setCanLoop(false);
                        } else {
                            mAdvBanner.setVisibility(View.VISIBLE);
                            mAdvBanner.setCanLoop(true);
                        }

                        mAdvBanner.setPages(() -> new AdvsImageHolderView(), advList)
                                .startTurning(4000)
                                .setPointViewVisible(false)
                                .canTouchScroll(false)
                                .setPageTransformer((page, position) -> {
                                    int pageWidth = page.getWidth();    //得到view宽

                                    if (position < -1) { // [-Infinity,-1)
                                        // This page is way off-screen to the left. 出了左边屏幕
                                        page.setAlpha(0);

                                    } else if (position <= 1) { // [-1,1]
                                        if (position < 0) {
                                            //消失的页面
                                            page.setTranslationX(-pageWidth * position);  //阻止消失页面的滑动
                                        } else {
                                            //出现的页面
                                            page.setTranslationX(pageWidth);        //直接设置出现的页面到底
                                            page.setTranslationX(-pageWidth * position);  //阻止出现页面的滑动
                                        }
                                        // Fade the page relative to its size.
                                        float alphaFactor = Math.max(MIN_ALPHA, 1 - Math.abs(position));
                                        //透明度改变Log
                                        page.setAlpha(alphaFactor);
                                    } else { // (1,+Infinity]
                                        // This page is way off-screen to the right.    出了右边屏幕
                                        page.setAlpha(0);
                                    }
                                })
                                .hideBannerText(true);
                    }

                } else if (list.get(i).getPosition().equals("-1")) {//上
                    if (list.get(i).getAdvertise() != null && list.get(i).getAdvertise().size() > 0) {
                        advTopList.clear();
                        advTopList.addAll(list.get(i).getAdvertise());
                        mAdvBannerTop.setVisibility(View.VISIBLE);

                        if (advTopList.size() == 0) {
                            mAdvBannerTop.setVisibility(View.GONE);
                        } else if (advTopList.size() == 1) {  //一张图时关闭轮播
                            mAdvBannerTop.setVisibility(View.VISIBLE);
                            mAdvBannerTop.setCanLoop(false);
                        } else {
                            mAdvBannerTop.setVisibility(View.VISIBLE);
                            mAdvBannerTop.setCanLoop(true);
                        }

                        mAdvBannerTop.setPages(() -> new AdvsImageHolderView(), advTopList)
                                .startTurning(4000)
                                .setPointViewVisible(false)
                                .canTouchScroll(false)
                                .setPageTransformer((page, position) -> {
                                    int pageWidth = page.getWidth();    //得到view宽

                                    if (position < -1) { // [-Infinity,-1)
                                        // This page is way off-screen to the left. 出了左边屏幕
                                        page.setAlpha(0);

                                    } else if (position <= 1) { // [-1,1]
                                        if (position < 0) {
                                            //消失的页面
                                            page.setTranslationX(-pageWidth * position);  //阻止消失页面的滑动
                                        } else {
                                            //出现的页面
                                            page.setTranslationX(pageWidth);        //直接设置出现的页面到底
                                            page.setTranslationX(-pageWidth * position);  //阻止出现页面的滑动
                                        }
                                        // Fade the page relative to its size.
                                        float alphaFactor = Math.max(MIN_ALPHA, 1 - Math.abs(position));
                                        //透明度改变Log
                                        page.setAlpha(alphaFactor);
                                    } else { // (1,+Infinity]
                                        // This page is way off-screen to the right.    出了右边屏幕
                                        page.setAlpha(0);
                                    }
                                })
                                .hideBannerText(true);
                    }

                }
            }

        } else {
            mAdvBanner.setVisibility(View.GONE);
            mAdvBannerTop.setVisibility(View.GONE);
            hasBottomAdv = false;
        }
    }

    @Override
    public void setGatherNews(List<GatherBean> beanList, final boolean isMore) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        List<GlobalNewsBean> indexList = new ArrayList<>();
        loadingMask.setStatus(LoadingLayout.Success);
        loadingMask.setReloadButtonText("点击重试~~");
        if (!isMore) {
            topNum = 0;
        }
        int globalCommon;
        int globalVideo;
        try {
            globalCommon = Integer.parseInt(CommonUtils.getInstance().getGlobalCommon());
            globalVideo = Integer.parseInt(CommonUtils.getInstance().getGlobalVideo());
        } catch (Exception e) {
            globalCommon = 0;
            globalVideo = 0;
        }

        //全局新闻样式配置
        for (int i = 0; i < beanList.size(); i++) {
            if ("2".equalsIgnoreCase(beanList.get(i).getType())) {
                beanList.get(i).getNews().setCommonStyle(globalCommon);
                beanList.get(i).getNews().setVideoStyle(globalVideo);
            }
        }

        try {  //获取最后一条新闻的id
            lastType = beanList.get(beanList.size() - 1).getType();
            switch (beanList.get(beanList.size() - 1).getType()) {
                case "5":
                    lastNewsId = beanList.get(beanList.size() - 1).getAdv().getId();
                    break;
                case "6":
                    lastNewsId = Integer.parseInt(beanList.get(beanList.size() - 1).getCatalog().getInnercode());
                    break;
                case "7":
                    lastNewsId = Integer.parseInt(beanList.get(beanList.size() - 1).getCatalog().getInnercode());
                    break;
                case "8":
                    lastNewsId = Integer.parseInt(beanList.get(beanList.size() - 1).getCatalog().getInnercode());
                    break;
                case "9":
                    lastNewsId = beanList.get(beanList.size() - 1).getLiveNews().getId();
                    break;
                case "10":
                    lastNewsId = beanList.get(beanList.size() - 1).getTopicInfo().getId();
                    break;
                case "11":
                    lastNewsId = beanList.get(beanList.size() - 1).getCircleTag().getId();
                    break;
                case "12":
                    lastNewsId = beanList.get(beanList.size() - 1).getBrokeNewsPlate().getId();
                    break;
                case "13":
                    lastNewsId = beanList.get(beanList.size() - 1).getBrokeNews().getBrokeNews().getId();
                    break;
                default:
                    lastNewsId = Integer.parseInt(beanList.get(beanList.size() - 1).getNews().getID());
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //转换数据模型
        for (int i = 0; i < beanList.size(); i++) {
            switch (beanList.get(i).getType()) {
                case "1"://置顶新闻
                    topNum++;
                    HomeBean.TopNews bean1 = beanList.get(i).getTop();
                    String type1 = "";
                    int newsStyle = 1;
                    switch (bean1.getType()) {
                        case "0":
                            type1 = "0";
                            break;
                        case "1"://普通新闻
                            type1 = "1";
                            break;
                        case "2"://图片新闻
                            type1 = "2";
                            break;
                        case "3"://直播
                            type1 = "9";
                            break;
                        case "4"://标题新闻
                            type1 = "8";
                            break;
                        case "5"://视频新闻
                            type1 = "3";
                            break;
                        case "8"://互动直播
                            bean1.setArticleID(bean1.getRoomId());//将roomId设置成通用Id
                            type1 = "5";
                            break;
                        case "101"://抓取新闻
                            type1 = "10";
                            break;
                        case "102"://小视频
                            type1 = "7";
                            break;
                        case "JLCommonNews":
                            newsStyle = 1;
                            type1 = "13";
                            break;
                        case "JLVideoNews":
                            newsStyle = 2;
                            type1 = "13";
                            break;
                        case "JLOutNews":
                            newsStyle = 3;
                            type1 = "13";
                            break;
                        default:
                            break;
                    }
                    if ("0".equals(type1)) {
                        if ("1".equals(bean1.getActivityJson().getType())) {
                            type1 = "11";//投票活动
                        } else {
                            type1 = "12";
                        }
                    }
                    //是否是无图
                    boolean hasPicture = StringUtils.isPictureSuccess(bean1.getArticleImg());
                    indexList.add(new GlobalNewsBean(bean1.getArticleTitle(), bean1.getArticleID(), bean1.getArticleURL(), bean1.getArticleImg(), newsStyle, null, "0", 0, null, bean1.getCatalogID(), hasPicture, type1, bean1.getLivetype()));
                    break;
                case "2"://新闻类型
                    NewsBean bean2 = beanList.get(i).getNews();
                    hasPicture = StringUtils.isPictureSuccess(bean2.getLogo());
                    String type = "", pOne = "", pTwo = "", pThree = "";
                    int style = 0;
                    switch (StringUtils.isEmpty(bean2.getType()) ? "10000" : bean2.getType()) {
                        case "1"://普通新闻
                            type = "1";
                            switch (bean2.getPluralPicsFlag()) {
                                case 0:
                                    style = bean2.getCommonStyle();
                                    break;
                                case 1://三图
                                    hasPicture = false;
                                    if (bean2.getImagess().size() == 1) {
                                        hasPicture = true;
                                        pOne = bean2.getImagess().get(0).getImageUrlString();
                                    } else if (bean2.getImagess().size() == 2) {
                                        pOne = bean2.getImagess().get(0).getImageUrlString();
                                        pTwo = bean2.getImagess().get(1).getImageUrlString();
                                        hasPicture = true;
                                    } else if (bean2.getImagess().size() >= 3) {
                                        pOne = bean2.getImagess().get(0).getImageUrlString();
                                        pTwo = bean2.getImagess().get(1).getImageUrlString();
                                        pThree = bean2.getImagess().get(2).getImageUrlString();
                                        hasPicture = true;
                                    } else {
                                        hasPicture = false;
                                    }
                                    style = 4;
                                    break;
                                case 2:
                                    style = 3;
                                    break;
                                default:
                                    style = bean2.getCommonStyle();
                                    break;
                            }
                            break;
                        case "2"://图片新闻
                            type = "2";
                            if (bean2.getImagess() == null || bean2.getImagess().size() < 1) {
                                continue;
                            }
                            if (bean2.getImagess().size() == 1) {
                                hasPicture = true;
                                pOne = bean2.getImagess().get(0).getImageUrlString();
                            } else if (bean2.getImagess().size() == 2) {
                                pOne = bean2.getImagess().get(0).getImageUrlString();
                                pTwo = bean2.getImagess().get(1).getImageUrlString();
                                hasPicture = true;
                            } else if (bean2.getImagess().size() >= 3) {
                                pOne = bean2.getImagess().get(0).getImageUrlString();
                                pTwo = bean2.getImagess().get(1).getImageUrlString();
                                pThree = bean2.getImagess().get(2).getImageUrlString();
                                hasPicture = true;
                            } else {
                                hasPicture = false;
                            }
                            break;
                        case "3"://直播
                            type = "9";
                            break;
                        case "4"://标题新闻
                            type = "8";
                            break;
                        case "5"://视频新闻
                            type = "3";
                            style = bean2.getVideoStyle();
                            break;
                        case "8"://互动直播
                            type = "5";
                            bean2.setID(bean2.getRoomId());//将roomId设置成通用Id
                            break;
                        case "101"://抓取新闻
                            type = "10";
                            break;
                        default:
                            break;
                    }
                    indexList.add(new GlobalNewsBean(bean2.getTitle(), bean2.getID(), bean2.getRedirectURL(), bean2.getLogo(), style, bean2.getPublishDate(), type, Integer.parseInt(bean2.getHitCount()), bean2.getSource(), bean2.getCatalogID(), hasPicture, pOne, pTwo, pThree, bean2.getLivetype(), bean2.getCommentCount()));
                    break;
                case "3"://小视频
                    NewsBean bean3 = beanList.get(i).getNews();
                    if (bean3 != null) {
                        indexList.add(new GlobalNewsBean(bean3.getTitle(), bean3.getID(), bean3.getLink(), bean3.getLogo(), 0, bean3.getPublishDate(), "7", bean3.getCommentCount(), bean3.getSource(), bean3.getCatalogID(), true, bean3.getLivetype()));
                    }
                    break;
                case "4"://新趣汇
                    NewsBean bean4 = beanList.get(i).getNews();
                    if (bean4 != null) {
                        indexList.add(new GlobalNewsBean(bean4.getTitle(), bean4.getID(), bean4.getRedirectURL(), bean4.getLogo(), 0, bean4.getPublishDate(), "6", Integer.parseInt(StringUtils.isNotEmpty(bean4.getHitCount()) ? bean4.getHitCount() : "0"), bean4.getSource(), bean4.getCatalogID(), true, bean4.getLivetype()));
                    }
                    break;
                case "5"://广告类型
                    AdvertiseBean bean = beanList.get(i).getAdv();
                    if (bean != null) {
                        GlobalNewsBean data = new GlobalNewsBean(bean.getTitle(), bean.getId() + "", bean.getLink(), bean.getImageUrl(), Integer.parseInt(bean.getStyle()), bean.getCatalogID(), "4", 0, bean.getContentType(), bean.getLinkId(), true, bean.getLinkType());
                        data.setIsShare(bean.getIsShare());
                        indexList.add(data);
                    }
                    break;
                case "6"://乡镇
                    UnionBean unionBean = beanList.get(i).getCatalog();
                    if (unionBean != null) {
                        indexList.add(new GlobalNewsBean(unionBean.getName(), unionBean.getInnercode() + "", "", unionBean.getLogo(), beanList.get(i).getPrejectStyle(), null, "11", 0, null, unionBean.getId(), true, null));
                    }
                    break;
                case "7"://政务
                    UnionBean unionBean1 = beanList.get(i).getCatalog();
                    if (unionBean1 != null) {
                        indexList.add(new GlobalNewsBean(unionBean1.getName(), unionBean1.getInnercode() + "", "", unionBean1.getLogo(), beanList.get(i).getPrejectStyle(), null, "12", 0, null, unionBean1.getId(), true, null));
                    }
                    break;
                case "8"://专题
                    UnionBean unionBean2 = beanList.get(i).getCatalog();
                    if (unionBean2 != null) {
                        indexList.add(new GlobalNewsBean(unionBean2.getName(), unionBean2.getInnercode() + "", "", unionBean2.getLogo(), beanList.get(i).getPrejectStyle(), null, "13", 0, null, unionBean2.getId(), true, null));
                    }
                    break;
                case "9"://图文直播
                    TeleTextBean teleTextBean = beanList.get(i).getLiveNews();
                    if (teleTextBean != null) {
                        indexList.add(new GlobalNewsBean(teleTextBean.getTitle(), teleTextBean.getId() + "", teleTextBean.getType(), teleTextBean.getCoverPic(), 0, teleTextBean.getCreatetime(), "14", Integer.parseInt(teleTextBean.getHits()), teleTextBean.getStatus(), teleTextBean.getChatroomId(), true, null));
                    }
                    break;
                case "10"://圈子
                    CircleHomeBean circleHomeBean = beanList.get(i).getTopicInfo();
                    int pictureNum = 0;
                    String picOne = "", picTwo = "", picThree = "";
                    hasPicture = false;
                    if (circleHomeBean != null) {
                        String topicName = null;
                        if (circleHomeBean.getTagList() != null && circleHomeBean.getTagList().size() > 0) {
                            topicName = circleHomeBean.getTagList().get(0).getName();
                        } else {
                            topicName = "";
                        }
                        if (circleHomeBean.getPicList() != null && circleHomeBean.getPicList().size() > 0) {
                            hasPicture = true;
                            if (circleHomeBean.getPicList().size() == 1) {
                                pictureNum = 1;
                                picOne = circleHomeBean.getPicList().get(0).getThumb();
                            } else if (circleHomeBean.getPicList().size() == 2) {
                                pictureNum = 2;
                                picOne = circleHomeBean.getPicList().get(0).getThumb();
                                picTwo = circleHomeBean.getPicList().get(1).getThumb();
                            } else if (circleHomeBean.getPicList().size() == 3) {
                                pictureNum = 3;
                                picOne = circleHomeBean.getPicList().get(0).getThumb();
                                picTwo = circleHomeBean.getPicList().get(1).getThumb();
                                picThree = circleHomeBean.getPicList().get(2).getThumb();
                            } else {
                                picOne = circleHomeBean.getPicList().get(0).getThumb();
                                picTwo = circleHomeBean.getPicList().get(1).getThumb();
                                picThree = circleHomeBean.getPicList().get(2).getThumb();
                                pictureNum = circleHomeBean.getPicList().size();
                            }
                        }
                        indexList.add(new GlobalNewsBean(circleHomeBean.getContent(), circleHomeBean.getId() + "", circleHomeBean.getVideo(), circleHomeBean.getVideoThumb(), "", circleHomeBean.getType()
                                , circleHomeBean.getGmtCreate(), "15", circleHomeBean.getPageview(), topicName, circleHomeBean.getUser().getNickName(), hasPicture, "", picOne, picTwo, picThree, pictureNum));
                    }
                    break;
                case "11"://圈子话题
                    CircleHomeBean.TagList circleTag = beanList.get(i).getCircleTag();
                    if (circleTag != null) {
                        indexList.add(new GlobalNewsBean(circleTag.getName(), circleTag.getId() + "", "", circleTag.getPic(), 0,
                                "", "16", 0, circleTag.getDesc(), "", true, ""));
                    }
                    break;
                case "12"://报料栏目
                    ScoopTopicBean scoopTopicBean = beanList.get(i).getBrokeNewsPlate();
                    if (scoopTopicBean != null) {
                        indexList.add(new GlobalNewsBean(scoopTopicBean.getName(), scoopTopicBean.getId() + "", "", "", 0, "",
                                "17", 0, "", "", false, ""));
                    }
                    break;
                case "13"://报料
                    ScoopListBean scoopListBean = beanList.get(i).getBrokeNews();
                    hasPicture = false;
                    String one = "", two = "", three = "";
                    int picNum = 0;
                    if (scoopListBean != null) {
                        if (scoopListBean.getImages() != null && scoopListBean.getImages().size() > 0) {
                            hasPicture = true;
                            if (scoopListBean.getImages().size() == 1) {
                                one = scoopListBean.getImages().get(0).getThumbnailUrl();
                            } else if (scoopListBean.getImages().size() == 2) {
                                one = scoopListBean.getImages().get(0).getThumbnailUrl();
                                two = scoopListBean.getImages().get(1).getThumbnailUrl();
                            } else if (scoopListBean.getImages().size() == 3) {
                                one = scoopListBean.getImages().get(0).getThumbnailUrl();
                                two = scoopListBean.getImages().get(1).getThumbnailUrl();
                                three = scoopListBean.getImages().get(2).getThumbnailUrl();
                            } else {
                                one = scoopListBean.getImages().get(0).getThumbnailUrl();
                                two = scoopListBean.getImages().get(1).getThumbnailUrl();
                                three = scoopListBean.getImages().get(2).getThumbnailUrl();
                                picNum = scoopListBean.getImages().size();
                            }
                        }
                        indexList.add(new GlobalNewsBean(scoopListBean.getBrokeNews().getTitle(), scoopListBean.getBrokeNews().getId() + "", scoopListBean.getBrokeNews().getUrl()
                                , scoopListBean.getBrokeNews().getCoverImgUrl(), scoopListBean.getBrokeNews().getStatus() + "", scoopListBean.getBrokeNews().getType(), scoopListBean.getBrokeNews().getCreatetime(), "18"
                                , scoopListBean.getBrokeNews().getClickAmount(), scoopListBean.getBrokePlate() != null ? scoopListBean.getBrokePlate().getName() : "", scoopListBean.getBrokeNews().getContent(), hasPicture, "", one, two, three, picNum));
                    }
                    break;
                case "14"://新活动
                    ActDetailsBean actDetailsBean = beanList.get(i).getActivity();
                    int personNum;
                    try {
                        personNum = actDetailsBean.getActivity().getActivity().getPageViews().intValue();
                    } catch (Exception e) {
                        personNum = 0;
                    }
                    if (actDetailsBean != null) {
                        indexList.add(new GlobalNewsBean(actDetailsBean.getActivity().getActivity().getActName(), actDetailsBean.getActivity().getActivity().getId() + "", "", actDetailsBean.getActivity().getActivity().getPosterUrl(),
                                0, actDetailsBean.getActivity().getActivity().getCreateTime(), "19", personNum, "", actDetailsBean.getActivity().getActivity().getDigest(), true, "19"));
                    }
                    break;
                default:
                    break;
            }
        }


        String advSwitch = CommonUtils.getInstance().getHomeAdv();
        if (advSwitch.equals("1") && indexList.size() >= 6 && !isCache && idNum < CommonUtils.getInstance().getPtgHomeId().length) {
            if (isMore) {
                int startPos = mDataList.size();
                mDataList.addAll(indexList);
                mHeaderAndFooterWrapper.notifyItemRangeChanged(startPos, indexList.size());
//                loadExpressAd();
            } else {
                if (hasBottomAdv) {
                    int index = 0;
                    for (int i = 0; i < indexList.size(); i++) {
                        if (indexList.get(i).getType().equals("0")) {
                            index++;
                        }
                    }
                    AdvertiseBean bean = advBottomList.get(0);
                    if (bean != null) {
                        GlobalNewsBean data = new GlobalNewsBean(bean.getTitle(), bean.getId() + "", bean.getLink(), bean.getImageUrl(), Integer.parseInt(bean.getStyle()), bean.getCatalogID(), "4", 0, bean.getContentType(), bean.getLinkId(), true, bean.getLinkType());
                        data.setIsShare(bean.getIsShare());
                        indexList.add(index, data);
                    }
                }
                idNum = 0;
                mDataList.clear();
                mDataList.addAll(indexList);
                mHeaderAndFooterWrapper.notifyDataSetChanged();
//                loadExpressAd();
            }
        } else {
            if (isMore) {
                mDataList.addAll(indexList);
            } else {
                mDataList.clear();

                if (hasBottomAdv) {
                    int index = 0;
                    for (int i = 0; i < indexList.size(); i++) {
                        if (indexList.get(i).getType().equals("0")) {
                            index++;
                        }
                    }
                    AdvertiseBean bean = advBottomList.get(0);
                    if (bean != null) {
                        GlobalNewsBean data = new GlobalNewsBean(bean.getTitle(), bean.getId() + "", bean.getLink(), bean.getImageUrl(), Integer.parseInt(bean.getStyle()), bean.getCatalogID(), "4", 0, bean.getContentType(), bean.getLinkId(), true, bean.getLinkType());
                        data.setIsShare(bean.getIsShare());
                        indexList.add(index, data);
                    }
                }
                mDataList.addAll(indexList);
            }
            mHeaderAndFooterWrapper.notifyDataSetChanged();
        }

        presenter.getTopShop();//获取是否存在置顶商品
    }


    @Override
    public void showError(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        Toasty.normal(getContext(), msg, Toast.LENGTH_SHORT).show();
        loadingMask.setStatus(LoadingLayout.Error);
        loadingMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void showMessage(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        if (page > 1) {
            page--;
        }
        Toasty.normal(getContext(), msg, Toast.LENGTH_SHORT).show();//显示信息
    }

    @Override
    public void showEmpty(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadingMask.setStatus(LoadingLayout.Success);
        loadingMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void setNavigation(boolean isShow, List<HomeBean.SecMenus> list) {
        if (isShow) {
            mNavigation.setVisibility(View.VISIBLE);
            mPointLayout.setVisibility(View.VISIBLE);
            classicEnterLayout.setVisibility(View.GONE);
            answerCover.setVisibility(View.GONE);
            partyEnter.setVisibility(View.GONE);
            navigationList.clear();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getTypeId() == 51) {
                    classicEnterLayout.setVisibility(View.VISIBLE);

                    Glide.with(HomeListFragment.this)
                            .load(list.get(i).getMenuImg())
                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                            .into(classicEnter);

                    classicEnter.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            RouterManager.router(ARouterPathConstant.CLASSIC_HOME);
                        }
                    });
                } else if (list.get(i).getTypeId() == 41) {
                    answerCover.setVisibility(View.VISIBLE);
                    HomeBean.SecMenus bean = list.get(i);

                    Glide.with(HomeListFragment.this)
                            .load(bean.getMenuImg())
                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                            .into(answerCover);

                    answerCover.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            bundle.putString("title", bean.getMenuName());
                            bundle.putString("id", "");
                            bundle.putBoolean("hasShare", false);
                            bundle.putBoolean("hasJS", true);
                            bundle.putString("url", bean.getUrl());
                            RouterManager.router(ARouterPathConstant.ADV, bundle);
                        }
                    });
                } else if (list.get(i).getTypeId() == 56) {
                    classicEnterLayout.setVisibility(View.VISIBLE);

                    HomeBean.SecMenus bean = list.get(i);
                    Glide.with(HomeListFragment.this)
                            .load(bean.getMenuImg())
                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                            .into(classicEnter);

                    classicEnter.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            bundle.putString("title", bean.getMenuName());
                            bundle.putString("id", bean.getUrl());
                            RouterManager.router(ARouterPathConstant.CLASSIC_DETAIL_NEW, bundle);
                        }
                    });
                } else if (list.get(i).getTypeId() == 58) {
                    partyEnter.setVisibility(View.VISIBLE);

                    HomeBean.SecMenus bean = list.get(i);
                    Glide.with(HomeListFragment.this)
                            .load(bean.getMenuImg())
                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                            .into(partyEnter);

                    partyEnter.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            RouterManager.routerLoginInterceptor(getContext(), ARouterPathConstant.PARTY_BUILDING_HOME);
                        }
                    });
                } else if (list.get(i).getTypeId() != 42) {
                    navigationList.add(list.get(i));
                }
            }
            mNavigation.setGridViewPagerDataAdapter(new GridViewPagerDataAdapter<HomeBean.SecMenus>(navigationList, ROWS_NUM, COLUMNS_NUM) {
                @Override
                public BaseAdapter getGridViewAdapter(List<HomeBean.SecMenus> currentList, int pageIndex) {
                    return new MyGridViewAdapter(getContext(), currentList);
                }

                @Override
                public void onItemClick(AdapterView parent, View view, int position, long id, int pageIndex) {
                    int mPosition = pageIndex * COLUMNS_NUM + position;
                    HomeBean.SecMenus bean = navigationList.get(mPosition);
                    navigationSkip(bean);//跳转
                }
            });

        } else {
            mNavigation.setVisibility(View.GONE);
            mPointLayout.setVisibility(View.GONE);
        }

        mPointLayout.removeAllViewsInLayout();
        if (navigationList == null || navigationList.isEmpty() || StringUtils.isEmpty(navigationList.get(0).getMenuImg())) {
            mPointLayout.setVisibility(View.GONE);
        } else {
            //滑动指示器
            try {
                imgs = new ImageView[mNavigation.getPageCount()];
                if (imgs.length < 2) {
                    mPointLayout.setVisibility(View.GONE);
                } else {
                    for (int i = 0; i < mNavigation.getPageCount(); i++) {
                        imgs[i] = new ImageView(getActivity());
                        if (i == 0) {
                            imgs[i].setImageResource(R.drawable.home_navigation_indicator_on);
                        } else {
                            imgs[i].setImageResource(R.drawable.home_navigation_indicator_off);
                        }
                        imgs[i].setPadding(5, 0, 5, 0);
                        mPointLayout.addView(imgs[i]);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void setTopShop(List<ShoppingListBean> bean) {
        if (bean != null && bean.size() > 0) {
            for (int i = 0; i < bean.size(); i++) {
                GlobalNewsBean shopbean = new GlobalNewsBean(bean.get(i).getItemName(), bean.get(i).getId() + "", bean.get(i).getItemPic(), bean.get(i).getItemType(), "20", bean.get(i).getStock(), bean.get(i).getPrice(), true, bean.get(i).getStatus());
                if (hasBottomAdv) {
                    topNum += 1;
                }
                mDataList.add(topNum, shopbean);
            }
            mHeaderAndFooterWrapper.notifyItemRangeChanged(topNum + 1, bean.size());
        }
    }

    private void navigationSkip(HomeBean.SecMenus bean) {
        switch (bean.getTypeId()) {
            case 1:
                if (bean.getStyleId() == 1) {//资讯样式
                    Bundle bundle = new Bundle();
                    bundle.putString("title", bean.getMenuName());
                    bundle.putString("id", bean.getSecondId() + "");
                    bundle.putString("type", "-1");
                    RouterManager.router(ARouterPathConstant.INFO, bundle);
                } else { //节目样式
                    Bundle bundle = new Bundle();
                    bundle.putString("title", bean.getMenuName());
                    bundle.putString("menuId", bean.getSecondId() + "");
                    bundle.putString("type", "-1");
                    RouterManager.router(ARouterPathConstant.PROGRAM, bundle);
                    ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.INFORMATION);
                }
                break;
            case 2://活动列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.ACTIVITY_LIST_TEMP, bundle);
            }
            break;
            case 3://直播列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.LIVELIST, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.LIVELIST);
            }
            break;
            case 4://链接
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("id", "");
                int hasShare = (int) AppConfigUtil.getInstance().getConValue(AppConfigConstant.LINK_URL_SHARE);
                bundle.putBoolean("hasShare", hasShare != 1);

                bundle.putString("url", bean.getUrl());
                bundle.putBoolean("hasJS", true);
                RouterManager.router(ARouterPathConstant.ADV, bundle);
            }
            break;
            case 5://电商
                break;
            case 6://新闻列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                if (bean.getStyleId() == 5) {
                    bundle.putString("catalogId", bean.getUrl());
                    bundle.putInt("type", 6);
                    RouterManager.router(ARouterPathConstant.NB_LIST, bundle);
                } else {
                    bundle.putString("id", bean.getUrl());
                    if (bean.getMenuName().equals("求职招聘")) {
                        bundle.putBoolean("hasSearch", true);
                    }
                    RouterManager.router(ARouterPathConstant.NEWS_LIST, bundle);
                }
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.SECTIONS);
            }
            break;
            case 7://新趣汇
            {
                RouterManager.router(ARouterPathConstant.GOOD_LIFE);
            }
            ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.GOODLIFE);
            break;
            case 8://小视频
            {
                RouterManager.router(ARouterPathConstant.SMALLVIDEO);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.SMALLVIDEO);
            }
            break;
            case 9:
                switch (bean.getStyleId()) {
                    case 1://乡镇
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", bean.getMenuName());
                        bundle.putString("sectionId", bean.getUrl());
                        RouterManager.router(ARouterPathConstant.TOWN_LIST, bundle);
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOWNDETAIL);
                    }
                    break;
                    case 2://政务
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", bean.getMenuName());
                        bundle.putString("sectionId", bean.getUrl());
                        RouterManager.router(ARouterPathConstant.GOV_LIST, bundle);
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.GOVDETAIL);
                    }
                    break;
                    case 3://专题
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", bean.getMenuName());
                        bundle.putString("sectionId", bean.getUrl());
                        if (bean.getMenuName().equals("乡村振兴")) {
                            bundle.putBoolean("hasSearch", true);
                        }
                        RouterManager.router(ARouterPathConstant.SPECIAL, bundle);
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.SPECIADETAIL);
                    }
                    break;
                    case 4://富顺乡镇样式
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", bean.getMenuName());
                        bundle.putString("sectionId", bean.getUrl());
                        RouterManager.router(ARouterPathConstant.UNION_TOWN3, bundle);
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOWNDETAIL);
                    }
                    break;
                    default:
                        Toasty.normal(getContext(), "类型出错！", Toast.LENGTH_SHORT).show();
                        break;
                }
                break;
            case 10://图文直播
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.TELETEXT_LIST, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TELETEXTLIST);
            }
            break;
            case 11://电视直播  1.广播 2.电视
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("id", bean.getUrl());
                bundle.putString("type", bean.getStyleId() + "");
                RouterManager.router(ARouterPathConstant.NEWLIVE_LIST, bundle);
            }
            break;
            case 12://传统直播混合列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("id", "");
                RouterManager.router(ARouterPathConstant.MIX_LIVE, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.MIXLIVE);
            }
            break;
            case 13:  //传统直播音频列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("id", "2");
                RouterManager.router(ARouterPathConstant.MIX_LIVE, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.MIXLIVE);
            }
            break;
            case 14: //传统直播视频列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("id", "1");
                RouterManager.router(ARouterPathConstant.MIX_LIVE, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.MIXLIVE);
            }
            break;
            case 15://新乡镇样式
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("id", bean.getUrl());
                RouterManager.router(ARouterPathConstant.UNION_TOWN2, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOWNDETAIL);
            }
            break;
            case 16://新活动
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.ACTIVITY_LIST_TEMP, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.ACTIVITY_LIST);
            }
            break;
            case 17://开票有喜
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("id", bean.getSecondId() + "");
                RouterManager.router(ARouterPathConstant.LUCK_DRAW, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.LUCK_DRA_HOME);
            }
            break;
            case 18://城事
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.CITY, bundle);
            }
            break;
            case 19://问答
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.SCOOP_HOME, bundle);
            }
            break;
            case 20: {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.COUPON_HOME_ACTIVITY, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.COUPON_HOME);
            }
            break;
            case 21://百事通
                RouterManager.router(ARouterPathConstant.BESTONE_TYPE);
                break;
            case 22: {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.NEWLIVE_LIST, bundle);
            }
            break;
            case 23: {//城阳资讯+ 报料
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("type", "-1");
                bundle.putString("id", bean.getSecondId() + "");
                RouterManager.router(ARouterPathConstant.INFO, bundle);
            }
            break;
            case 24: {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putInt("type", 0);
                RouterManager.router(ARouterPathConstant.JL_LIST, bundle);
            }
            break;
            case 25: {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putInt("type", 1);
                RouterManager.router(ARouterPathConstant.JL_LIST, bundle);
            }
            break;
            case 26: {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.JL_MULTI_LIST, bundle);
            }
            break;
            case 29:
            case 37: {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getUrl());
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.PRACTICE_HOME, bundle);
            }
            break;
            case 45:
                RouterManager.router(ARouterPathConstant.QUESTION_HOME);
                break;
            case 49: {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.SHOP_LIST, bundle);
            }
            break;
            case 52: {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("menuId", bean.getSecondId() + "");
                bundle.putString("type", "-1");
                bundle.putBoolean("hasNew", false);
                RouterManager.router(ARouterPathConstant.NB_LIST, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.INFORMATION);
            }
            break;
            case 53: {
                RouterManager.router(ARouterPathConstant.SCHOOL_HOME);
            }
            break;
            case 55: {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.NANBU_LIVE, bundle);
            }
            break;
            case 56: {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("id", bean.getUrl());
                RouterManager.router(ARouterPathConstant.CLASSIC_DETAIL_NEW, bundle);
            }
            break;
            case 57: {
                String appId = CommonUtils.getInstance().getSHARE_WEIXIN_APPID(); // 填移动应用(App)的 AppId，非小程序的 AppID
                IWXAPI api = WXAPIFactory.createWXAPI(getContext(), appId);

                WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                req.userName = "gh_c5e311f36f6f"; // 填小程序原始id
                req.path = bean.getUrl();
                ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                api.sendReq(req);
            }
            break;
            case 59: {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SHOP_HOME)
                        .withString("title", bean.getMenuName())
                        .navigation();
            }
            break;
            case 63: {
                boolean b = checkAppInstalled(getActivity(), "com.ss.android.ugc.aweme");
                if (b) {
                    Intent intent = new Intent();
                    intent.setData(Uri.parse("snssdk1128://user/profile/" + bean.getUrl()));
                    startActivity(intent);
                } else {
                    ToastUtils.showToast(getActivity(), "未安装此应用");
                }
            }
            break;
            default: {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.ACTIVITY_DEFAULT, bundle);
            }
            break;
        }
    }

    @Override
    public void onDestroy() {
        presenter.onDestroy();
        super.onDestroy();
    }

    public void getData() {
        presenter.getGatherData(page, lastNewsId, lastType);
    }

    /**
     * 顶部轮播holder
     */
    class BannerImageHolderView implements SimpleHolder<HomeBean.TopNews> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, HomeBean.TopNews data) {
            Glide.with(context.getApplicationContext())
                    .load(data.getArticleImg())
                    .apply(options)
                    .into(imageView);
        }
    }

    /**
     * 广告轮播holder
     */
    class AdvsImageHolderView implements SimpleHolder<AdvertiseBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, AdvertiseBean data) {
            Glide.with(context.getApplicationContext())
                    .load(data.getImageUrl())
                    .apply(new RequestOptions().placeholder(R.drawable.adv_group_no_img).error(R.drawable.adv_group_no_img))
                    .into(imageView);

        }

    }

    //设置滑动指示器
    private void setIndicator(int position) {
        for (int i = 0; i < imgs.length; i++) {
            if (i == position) {
                imgs[i].setImageResource(R.drawable.home_navigation_indicator_on);
            } else {
                imgs[i].setImageResource(R.drawable.home_navigation_indicator_off);
            }
        }
    }

    private boolean checkAppInstalled(Context context, String pkgName) {
        if (pkgName == null || pkgName.isEmpty()) {
            return false;
        }
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> info = packageManager.getInstalledPackages(0);
        if (info == null || info.isEmpty())
            return false;
        for (int i = 0; i < info.size(); i++) {
            if (pkgName.equals(info.get(i).packageName)) {
                return true;
            }
        }
        return false;
    }


}
